<template>
  <div class="box">
    <el-tree 
      ref="tree" 
      class="nav-tree" 
      :data="res" 
      v-if="defaultCheckedKeys.length"
      show-checkbox node-key="id" 
      @check-change="handleCheckChange"
      :default-checked-keys="defaultCheckedKeys" 
      :props="defaultProps" />
    <div v-for="(e, i) in res" :key="i" class="chart-item-box">
      <div class="chart-item" v-for="(item, index) in e.children" :key="index">
        <chart :option="item" />
      </div>
    </div>
  </div>
</template>

<script>
import chart from './module/chart'
export default {
  data() {
    return {
      res: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultCheckedKeys: []
    };
  },
  components: {
    chart
  },
  async mounted() {
    this.fakeData()
    this.$nextTick(() => {
      let position = this.getElementPagePosition(this.$refs.tree.$el)
      this.$refs.tree.$el.style.position = 'fixed'
      this.$refs.tree.$el.style.left = `${position.x}px`
      this.$refs.tree.$el.style.top = `${position.y}px`
    })
  },
  methods: {
    fakeData() {
      let type = ['scatter', 'bar', 'line', 'pie']
      for (let i=0; i < 6; i++) {
        let children = []
        let data = []
        for (let i = 0; i < 50; i ++) {
          data.push([i, parseInt(Math.random() * 50)])
          // pie 需要name
        }
        for (let j = 0; j < 4; j ++) {
          children.push({
            label: `指标${i*4 + 1 + j}`,
            id: i*4 + 1 + j,
            type: type[parseInt(Math.random() * 4)],
            // type: type[4],
            data
          })
        }
        let temp = {
          label: `指标分类${i + 1}`,
          id: i * 4,
          children
        }
        this.res.push(temp)
      }
      console.log(this.res)
      this.handleDefaultCheckedKeys()
    },
    handleDefaultCheckedKeys() {
      this.res.forEach(e => {
        e.children && e.children.forEach(item => {
          this.defaultCheckedKeys.push(item.id)
        })
      })
    },
    handleCheckChange(data, checked) {
      console.log(data, checked);
      // if (checked) {
        
      // }
    },
    getElementPagePosition(element){
      var actualLeft = element.offsetLeft;
      var actualTop = element.offsetTop;
      var current = element.offsetParent;
      while (current !== null){
        actualLeft += current.offsetLeft;
        actualTop += (current.offsetTop+current.clientTop);
        current = current.offsetParent;
      }
      return {x: actualLeft, y: actualTop}
    }
  },
}
</script>
<style lang="less" scoped>
.box{
  padding: 16px 0 0 216px;
  position: relative;
  .nav-tree{
    width: 200px;
    padding: 16px;
    box-sizing: border-box;
    position: absolute;
    left: 0;
    top: 16px;
  }
}
.chart-item-box{
  overflow: hidden;
  .chart-item{
    float: left;
    width: 50%;
    height: 400px;
  }
}
</style>